package com.plugin.manage.test;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;

//@Configuration
public class ScheduleConfig {

    @Scheduled(fixedRate = 60) // 每秒检查一次，实际中可以设置为更大值，比如1分钟或更长
    public void scheduleTaskWithRandomDelay() {
        LocalTime now = LocalTime.now();
        LocalTime randomTime = now.plus(Duration.ofHours(ThreadLocalRandom.current().nextLong(0, 24)));
                //now.plus(Duration.ofMinutes(ThreadLocalRandom.current().nextLong(0, 2)));
        // // 随机选择今天内的任何时间点
        System.out.println("Random time: " + randomTime);
        LocalDateTime scheduleTime = LocalDateTime.of(LocalDate.now(), randomTime); // 确保时间是今天的随机时间点
        long delay = Duration.between(LocalDateTime.now(), scheduleTime).toMillis(); // 计算延迟时间（毫秒）
        if (delay <= 0) { // 如果当前时间已经超过随机时间，则延迟到明天的随机时间
            scheduleTime = scheduleTime.plusDays(1); // 延迟到明天的随机时间点
            delay = Duration.between(LocalDateTime.now(), scheduleTime).toMillis();// 重新计算延迟时间（毫秒）
            System.out.println("Delayed to: " + scheduleTime);
        }
        try {
            Thread.sleep(delay); // 线程休眠直到随机时间点
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // 恢复中断状态
        }
        // 执行任务...
        executeTask();
    }

    private void executeTask() {
        System.out.println("Task executed at: " + LocalTime.now()); // 模拟任务执行
    }
}